package com.example.apidemo.file;


import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.MalformedURLException;
import java.nio.file.*;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/files")
public class FileController {
    private String makeFileName(String filename) {
        // 为防止文件覆盖的现象发生，要为上传文件产生一个唯一的文件名
        return UUID.randomUUID().toString() + "_" + filename;
    }


    private static final String UPLOAD_DIR = "./uploads/";

    ///上传文件
    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new ResponseEntity<>("Please select a file to upload", HttpStatus.BAD_REQUEST);
        }

        try {
            String fileName = file.getOriginalFilename();


            byte[] bytes = file.getBytes();
            Path path = Paths.get(UPLOAD_DIR + UUID.randomUUID() + "_" + fileName);
            Files.write(path, bytes);

            return new ResponseEntity<>("File uploaded successfully: " + path.toFile().getName(), HttpStatus.OK);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseEntity<>("Could not upload the file: " + e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PostMapping("/upload/multiple")
    public ResponseEntity<String> uploadMultipleFiles(@RequestParam("files") List<MultipartFile> files) {
        for (MultipartFile file : files) {
            uploadFile(file);
        }
        return new ResponseEntity<>("Multiple files uploaded successfully", HttpStatus.OK);
    }


    @GetMapping("/download")
    public ResponseEntity<Resource> download(@RequestParam("file") String name) throws IOException {
        // 创建文件路径
        Path filePath = Paths.get(UPLOAD_DIR + name);
        Resource file = new FileSystemResource(filePath);

        if (file.exists() || file.isReadable()) {
            // 设置响应头
            String fileName = filePath.getFileName().toString();
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName);
            headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);

            // 创建响应实体
            return ResponseEntity.ok()
                    .headers(headers)
                    .body(file);
        } else {
            // 文件不存在或不可读
            return ResponseEntity.notFound().build();
        }
    }

    ///使用方式：/// http://127.0.0.1:8080/files/download/a50362b3-a0d7-495c-8035-61df4f7b2fa6_815f3710312664d3d7d07e21d763b36.png
    // @SneakyThrows
    @GetMapping("/download/{fileName:.+}")
    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName) {
        Path filePath = Paths.get(UPLOAD_DIR + fileName);
        if (!Files.exists(filePath)) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }

        Resource resource = null;
        try {
            resource = new UrlResource(filePath.toUri());
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
                .body(resource);
    }

    // 断点下载功能比较复杂，通常需要前端配合，以下仅为简化示例

}
